﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sykj.IServices;
using Sykj.Components;
using Sykj.Entity;

namespace Sykj.Web.Areas.Manager.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class CmsController : MController
    {
        IModule _module;
        IChannel _channel;
        IContent _content;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="module"></param>
        /// <param name="channel"></param>
        /// <param name="content"></param>
        public CmsController(IModule module, IChannel channel, IContent content)
        {
            _module = module;
            _channel = channel;
            _content = content;
        }

        #region 栏目

        /// <summary>
        /// 栏目
        /// </summary>
        /// <returns></returns>
        public IActionResult ChannelIndex()
        {
            return View();
        }

        /// <summary>
        /// 栏目列表
        /// </summary>
        /// <param name="keyWords">关键词搜索</param>
        /// <returns></returns>
        public IActionResult ChannelList(string keyWords)
        {
            StringBuilder strWhere = new StringBuilder(" 1=1 ");
            if (!string.IsNullOrWhiteSpace(keyWords))
            {
                strWhere.Append(" AND channeName.Contains(@0)");
            }
            var list = _channel.GetList(0, strWhere.ToString(), " channelID desc ", keyWords).ToList();
            int recordCount = _channel.GetRecordCount(strWhere.ToString(), keyWords);
            return Json(ListResult(list, recordCount));
        }

        /// <summary>
        /// 添加栏目
        /// </summary>
        /// <returns></returns>
        public IActionResult ChannelAdd(int id)
        {
            ViewBag.ModuleAll = new SelectList(_module.GetList().ToList(), "ModuleId", "TypeName");
            ViewBag.ChannelAll = BindDropList();
            if (id > 0)
            {
                var model = _channel.GetModel(c => c.ChannelId == id);
                return View(model);
            }
            return View();
        }

        /// <summary>
        /// 下拉选择
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetDatas()
        {
            ViewBag.ChannelAll = BindDropList();
            return Json(Success("操作成功！"));
        }

        /// <summary>
        /// 添加栏目
        /// </summary>
        /// <param name="model">栏目信息</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ChannelAdd(Entity.Channel model)
        {
            bool b = _channel.CreateChannel(model);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 编辑栏目
        /// </summary>
        /// <param name="id">栏目id</param>
        /// <returns></returns>
        public IActionResult ChannelEdit(int id)
        {
            ViewBag.ModuleAll = new SelectList(_module.GetList(), "ModuleId", "TypeName");
            ViewBag.ChannelAll = BindDropList();
            var model = _channel.GetModel(c => c.ChannelId == id);

            if (model == null)
            {
                return Content("查询不到数据！");
            }

            return View(model);
        }

        /// <summary>
        /// 保存栏目编辑
        /// </summary>
        /// <param name="Channel">栏目模型</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ChannelEdit(Entity.Channel Channel)
        {
            var model = _channel.GetModel(c => c.ChannelId == Channel.ChannelId);
            if (model == null)
            {
                return Json(Failed("查询不到数据"));
            }
            model.ParentId = Channel.ParentId;
            model.ChanneName = Channel.ChanneName;
            model.Description = Channel.Description;
            model.ImageUrl = Channel.ImageUrl;
            model.ParentId = Channel.ParentId;
            model.Keywords = Channel.Keywords;
            model.Remark = Channel.Remark;
            model.Status = Channel.Status;
            bool b = _channel.Update(model);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ChannelDel(int id)
        {
            var model = _channel.GetModel(c => c.ChannelId == id);

            if (model == null)
            {
                return Content("查询不到数据！");
            }

            bool b = _channel.Delete(model);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 绑定下拉列表信息
        /// </summary>
        public List<SelectListItem> BindDropList()
        {
            List<SelectListItem> itemList = new List<SelectListItem>();
            itemList.Add(new SelectListItem { Text = "请选择栏目", Value = "0" });

            var listAll = _channel.GetList().ToList();
            if (listAll.Count > 0)
            {
                var listOne = listAll.Where(c => c.ParentId == 0);
                SelectListItem selectItem;
                foreach (var item in listOne)
                {
                    string text = item.ChanneName;
                    text = "╋" + text;
                    selectItem = new SelectListItem
                    {
                        Text = text,
                        Value = item.ChannelId.ToString()
                    };
                    string blank = "├";
                    itemList.Add(selectItem);

                    BiudTree(item.ChannelId, itemList, listAll, blank);
                }
            }
            return itemList;
        }

        /// <summary>
        /// 递归查询，绑定select
        /// </summary>
        /// <param name="pId"></param>
        /// <param name="itemList"></param>
        /// <param name="dataList"></param>
        /// <param name="blank"></param>
        private void BiudTree(int pId, List<SelectListItem> itemList, List<Entity.Channel> dataList, string blank)
        {
            var list = dataList.Where(c => c.ParentId == pId);
            SelectListItem selectItem;
            foreach (var item in list)
            {
                string text = item.ChanneName;
                text = blank + "『" + text + "』";

                selectItem = new SelectListItem
                {
                    Text = text,
                    Value = item.ChannelId.ToString()
                };

                itemList.Add(selectItem);
                string blank2 = blank + "─";
                BiudTree(item.ChannelId, itemList, dataList, blank2);
            }
        }

        #endregion

        #region 文章

        /// <summary>
        /// 文章列表
        /// </summary>
        /// <returns></returns>
        public IActionResult ContentIndex()
        {
            return View();
        }

        /// <summary>
        /// 栏目列表
        /// </summary>
        /// <param name="page">起始页</param>
        /// <param name="limit">页大小</param>
        /// <param name="keyWords">关键系</param>
        /// <param name="sortField"></param>
        /// <param name="sortType"></param>
        /// <param name="status">状态</param>
        /// <param name="channelId">栏目id</param>>
        /// <returns></returns>
        public IActionResult ContentList(int page, int limit, string keyWords,
            string sortField, string sortType, int status, int channelId)
        {
            StringBuilder strWhere = new StringBuilder(" 1=1 ");
            if (!string.IsNullOrWhiteSpace(keyWords))
            {
                strWhere.Append(" AND Title.Contains(@0)");
            }

            if (status > 0)
            {
                strWhere.Append(" AND Status=@1 ");
            }

            string orderStr = "ContentId DESC";

            if (channelId > 0)
            {
                strWhere.Append(" AND ChannelId=@2  ");
            }

            if (!string.IsNullOrWhiteSpace(sortField) && !string.IsNullOrWhiteSpace(sortType))
            {
                orderStr = sortField + " " + sortType;
            }

            var list = _content.GetPagedList(page, limit, strWhere.ToString(), orderStr, keyWords, status, channelId);
            int recordCount = _content.GetRecordCount(strWhere.ToString(), keyWords, status, channelId);
            return Json(ListResult(list, recordCount));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult ChannelTreeList()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult GetChannelTreeList()
        {
            StringBuilder strWhere = new StringBuilder(" 1=1 ");
            var channelList = _channel.GetList(0, strWhere.ToString(), "").ToList();

            channelList.Insert(0, new Channel() { ChannelId = 0, ChanneName = "全部", ParentId = 0 });

            var list = channelList.Select(c => new { id = c.ChannelId, pId = c.ParentId, name = c.ChanneName, open = true });
            return Json(list);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult GetChannelTreeListBySiteId()
        {
            StringBuilder strWhere = new StringBuilder(" 1=1 ");
            var channelList = _channel.GetList(0, strWhere.ToString(), "").ToList();

            channelList.Insert(0, new Channel() { ChannelId = 0, ChanneName = "全部", ParentId = 0 });

            var list = channelList.Select(c => new { id = c.ChannelId, pId = c.ParentId, name = c.ChanneName, open = true });
            return Json(list);
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        public IActionResult ContentDel(int id)
        {
            var model = _content.GetModel(c => c.ContentId == id);

            if (model == null)
            {
                return Content("查询不到数据！");
            }

            bool b = _content.Delete(model);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 添加文章
        /// </summary>
        /// <returns></returns>
        public IActionResult ContentAdd()
        {
            return View();
        }

        /// <summary>
        /// 保存添加文章
        /// </summary>
        /// <param name="content">文章信息</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ContentAdd(Sykj.Entity.Content content)
        {

            content.CreateDate = DateTime.Now;
            content.Status = 1;
            content.CreateUserId = UserId;
            bool b = _content.Add(content);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        public IActionResult ContentEdit(int id)
        {
            var model = _content.GetModel(c => c.ContentId == id);

            if (model == null)
            {
                return Content("查询不到数据！");
            }

            model.ChannelName = _channel.GetModel(c => c.ChannelId == model.ChannelId).ChanneName;

            return View(model);
        }

        /// <summary>
        /// 编辑保存
        /// </summary>
        /// <param name="Content"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ContentEdit(Sykj.Entity.Content Content)
        {
            var model = _content.GetModel(c => c.ContentId == Content.ContentId);
            if (model == null)
            {
                return Json(Failed("查询不到数据"));
            }
            model.ChannelId = Content.ChannelId;
            model.Title = Content.Title;
            model.SubTitle = Content.SubTitle;
            model.Description = Content.Description;
            model.ImageUrl = Content.ImageUrl;
            model.Status = Content.Status;
            model.Sort = Content.Sort;
            model.BeFrom = Content.BeFrom;
            model.LinkUrl = Content.LinkUrl;
            model.Keywords = Content.Keywords;
            model.Remary = Content.Remary;

            bool b = _content.Update(model);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="contentId">文章id</param>
        /// <param name="sort">排序</param>
        /// <param name="field">文件</param>
        /// <returns></returns>
        public IActionResult ContentModify(int contentId, int sort, string field)
        {
            var model = _content.GetModel(c => c.ContentId == contentId);

            if (model == null)
            {
                return Content("查询不到数据！");
            }

            if (field == "sort")
            {
                model.Sort = sort;
            }

            bool b = _content.Update(model);

            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">ids</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DeleteAll(List<int> ids)
        {
            var list = _content.GetList(c => ids.Contains(c.ContentId));
            bool b = _content.Delete(list);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 批量发布
        /// </summary>
        /// <returns></returns>
        public IActionResult ContentAudit(List<int> ids)
        {
            var list = _content.GetList(c => ids.Contains(c.ContentId)).ToList();
            list.ForEach(c => c.Status = 2);
            bool b = _content.UpdateRange(list);
            return Json(AjaxResult(b));
        }

        /// <summary>
        /// 批量取消发布
        /// </summary>
        /// <returns></returns>
        public IActionResult ContentNoAudit(List<int> ids)
        {
            var list = _content.GetList(c => ids.Contains(c.ContentId)).ToList();
            list.ForEach(c => c.Status = 1);
            bool b = _content.UpdateRange(list);
            return Json(AjaxResult(b));
        }
        #endregion

        /// <summary>
        /// 绑定下拉列表信息
        /// </summary>
        public IActionResult BindDropListExp()
        {
            List<Entity.Channel> itemList = new List<Entity.Channel>();

            var listAll = _channel.GetList().ToList();
            if (listAll.Count > 0)
            {
                var listOne = listAll.Where(c => c.ParentId == 0);
                foreach (var item in listOne)
                {
                    string text = item.ChanneName;
                    text = "╋" + text;
                    string blank = "├";
                    item.ChanneName = text;
                    itemList.Add(item);

                    BiudTreeExp(item.ChannelId, itemList, listAll, blank);
                }
            }
            return Json(DataResult(itemList));
        }

        /// <summary>
        /// 递归查询，绑定select
        /// </summary>
        /// <param name="pId"></param>
        /// <param name="itemList"></param>
        /// <param name="dataList"></param>
        /// <param name="blank"></param>
        private void BiudTreeExp(int pId, List<Entity.Channel> itemList, List<Entity.Channel> dataList, string blank)
        {
            var list = dataList.Where(c => c.ParentId == pId);
            foreach (var item in list)
            {
                string text = item.ChanneName;
                text = blank + "『" + text + "』";
                item.ChanneName = text;
                itemList.Add(item);
                string blank2 = blank + "─";
                BiudTreeExp(item.ChannelId, itemList, dataList, blank2);
            }
        }
    }
}